import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/assets/styles.dart';
import 'package:pornhub_app/components/diolog/provinces_city/provinces_city_dialog.dart';
import 'package:pornhub_app/components/easy_toast.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/components/keep_alive_wrapper.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/model/arround/query_model.dart';
import 'package:pornhub_app/utils/color.dart';

import 'package:pornhub_app/utils/events.dart';
import 'package:pornhub_app/utils/extension.dart';

import 'package:pornhub_app/views/blogger/views/blogger_list_page_view.dart';
import '../controllers/blogger_page_controller.dart';

class BloggerPage extends StatefulWidget {
  const BloggerPage({super.key});

  @override
  State<BloggerPage> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<BloggerPage> {
  final controller = Get.find<BloggerPageController>();

  StreamSubscription? streamSubscription;
  StreamSubscription? clearLocationEvent;
  @override
  void initState() {
    clearLocationEvent = eventBus.on<ClearLocationEvent>().listen((event) {
      if (event.loadType == 1) {
        controller.currentItems[0] = "";
      } else {
        controller.currentItems[1] = controller.userService.user.cityName;
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(0, 0, 0, 0.5),
      appBar: AppBar(
        titleSpacing: 2.w,
        title:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Obx(() => Row(
                children: [
                  Text(
                    "在线",
                    style: kTextStyle(
                        controller.currentIndex.value == 0
                            ? Styles.color.whiteText
                            : Styles.color.color898A8E,
                        fontsize:
                            controller.currentIndex.value == 0 ? 22.w : 16.w),
                  ).marginOnly(left: 14.w, right: 15.w).onTap(() {
                    if (controller.currentIndex.value != 0) {
                      controller.currentIndex.value = 0;
                      controller.pageController.jumpToPage(0);
                    }
                  }),
                  Text(
                    "同城",
                    style: kTextStyle(
                        controller.currentIndex.value == 1
                            ? Styles.color.whiteText
                            : Styles.color.color898A8E,
                        fontsize:
                            controller.currentIndex.value == 1 ? 22.w : 16.w),
                  ).marginOnly(left: 15.w, right: 15.w).onTap(() {
                    if (controller.currentIndex.value != 1) {
                      controller.currentIndex.value = 1;
                      controller.pageController.jumpToPage(1);
                    }
                  }),
                ],
              )),
          Row(
            children: [
              Obx(() => Row(
                    children: [
                      if (controller.currentItems[controller.currentIndex.value]
                          .isNotEmpty)
                        Text(
                          controller.currentItems[
                                      controller.currentIndex.value] ==
                                  controller.userService.user.cityName
                              ? "当前"
                              : controller
                                  .currentItems[controller.currentIndex.value],
                          style: kTextStyle(
                            Styles.color.colorCD73FB,
                            fontsize: 16.w,
                          ),
                        ).marginOnly(right: 12.w),
                      ImageView(
                        src: AppImagePath.arround_icon_location,
                        width: 16.w,
                        height: 20.w,
                      )
                    ],
                  ).onTap(() async {
                    // await getCurrentLocation();
                    showAlertCityPicker(context, confirm: (tuple) {
                      controller.currentItems[controller.currentIndex.value] =
                          "${tuple.item4}";
                      controller.currentCity.value = "${tuple.item4}";
                      controller.currentProvince.value = "${tuple.item2}";

                      eventBus.fire(LocationEvent(
                          controller.currentIndex.value + 1,
                          tuple.item2,
                          tuple.item4));
                      if (mounted) {
                        setState(() {});
                      }
                    });
                  })),
              Obx(() => ImageView(
                    src: controller.enableQuery.value
                        ? AppImagePath.arround_icon_filter_on
                        : AppImagePath.arround_icon_filter_off,
                    width: 20.w,
                    height: 16.w,
                  ).marginOnly(left: 24.w, right: 14.w).onOpaqueTap(() async {
                    var res = await showFilterAction();

                    if (res != null) {
                      controller.query.value = res;
                      controller.enableQuery.value = res.enableQuery;
                      res.cityName = controller.currentCity.value;
                      controller.update();
                      eventBus.fire(QueryEvent(res));
                    }
                  })),
            ],
          )
        ]),
      ),
      body: PageView(
        controller: controller.pageController,
        children: [
          KeepAliveWrapper(
              child: BloggerListPageView(
            city: controller.currentCity.value,
            province: controller.currentProvince.value,
            loadType: 1,
          )),
          KeepAliveWrapper(
              child: Obx(() => BloggerListPageView(
                    city: controller.currentCity.value,
                    province: controller.currentProvince.value,
                    loadType: 2,
                  )))
        ],
        onPageChanged: (value) {
          controller.currentIndex.value = value;
        },
      ),
    );
  }

  Future<void> getCurrentLocation() async {
    // if (!controller.showLocation.value) {
    //   bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    //   if (!serviceEnabled) {
    //     EasyToast.show('请打开定位服务');
    //     return;
    //   }
    //   LocationPermission permission = await Geolocator.checkPermission();
    //   if (permission == LocationPermission.denied) {
    //     permission = await Geolocator.requestPermission();
    //   }
    //   if (permission == LocationPermission.whileInUse ||
    //       permission == LocationPermission.always) {
    //     try {
    //       Position position = await Geolocator.getCurrentPosition();
    //       controller.showLocation.value = true;
    //       // You can now use position.latitude and position.longitude
    //       print(
    //           "Latitude: ${position.latitude}, Longitude: ${position.longitude}");
    //     } catch (e) {
    //       controller.showLocation.value = false;
    //       EasyToast.show('获取位置失败');
    //     }
    //   }
    // }
  }

  Future<QueryModel?> showFilterAction() async {
    String? bodyShape = controller.query.value.bodyShape;
    String? emotion = controller.query.value.emotion;
    bool enableQuery = controller.query.value.enableQuery;
    int endAge = controller.query.value.endAge;
    int endHeight = controller.query.value.endHeight;
    int endWeight = controller.query.value.endWeight;
    String? intention = controller.query.value.intention;
    String? prefer = controller.query.value.prefer;
    int startAge = controller.query.value.startAge;
    int startHeight = controller.query.value.startHeight;
    int startWeight = controller.query.value.startWeight;
    return await Get.bottomSheet(StatefulBuilder(builder: (context, setState) {
      return Container(
        height: 648.w,
        padding: EdgeInsets.all(16.w),
        width: double.infinity,
        decoration: BoxDecoration(
            color: COLOR.color_111,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(14.w),
                topRight: Radius.circular(14.w))),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Container(
                      margin: EdgeInsets.only(bottom: 4.w),
                      height: 24.w,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "筛选开关",
                        style: kTextStyle(COLOR.white, fontsize: 16.w),
                      ),
                    ),
                    Container(
                      width: 52.w,
                      height: 24.w,
                      margin: EdgeInsets.only(left: 12.w),
                      padding: EdgeInsets.only(right: 2.w, left: 2.w),
                      decoration: BoxDecoration(
                          color: enableQuery
                              ? COLOR.hexColor("#B93FFF")
                              : COLOR.hexColor("#DFDFDF"),
                          borderRadius: BorderRadius.circular(18.w)),
                      child: Row(
                        mainAxisAlignment: enableQuery
                            ? MainAxisAlignment.end
                            : MainAxisAlignment.start,
                        children: [
                          Container(
                            width: 19.w,
                            height: 19.w,
                            decoration: BoxDecoration(
                                color: COLOR.white,
                                borderRadius: BorderRadius.circular(19.w)),
                          )
                        ],
                      ),
                    ).onOpaqueTap(() {
                      enableQuery = !enableQuery;
                      setState(() {});
                    })
                  ],
                ),
                ImageView(
                  src: AppImagePath.mine_icon_dialog_close_white,
                  width: 16.w,
                  height: 16.w,
                ).onTap(() {
                  Get.showDialog(
                    nextText: "保存",
                    backText: "放弃",
                    content: "确定放弃修改筛选项吗？",
                    nextTap: () {
                      Get.back(
                          result: QueryModel(
                        enableQuery: enableQuery,
                        loadType: controller.currentIndex.value + 1,
                        bodyShape: bodyShape,
                        emotion: emotion,
                        endAge: endAge,
                        endHeight: endHeight,
                        endWeight: endWeight,
                        intention: intention,
                        prefer: prefer,
                        startAge: startAge,
                        startHeight: startHeight,
                        startWeight: startWeight,
                      ));
                    },
                    backTap: () {
                      Get.back(result: null);
                    },
                  );
                })
              ],
            ),
            Expanded(
                child: ListView(
              children: [
                Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("身高",
                            style: kTextStyle(COLOR.white, fontsize: 12.w)),
                        Text(
                            startHeight == 0 && endHeight == 220
                                ? "不限"
                                : "$startHeight-$endHeight cm",
                            style: kTextStyle(
                                enableQuery
                                    ? COLOR.hexColor("#B93FFF")
                                    : COLOR.white,
                                fontsize: 12.w)),
                      ],
                    ).marginBottom(12.w),
                    SizedBox(
                      width: 400.w,
                      child: RangeSlider(
                        values: RangeValues(
                            startHeight.toDouble(), endHeight.toDouble()),
                        min: 0,
                        max: 220,
                        onChanged: enableQuery
                            ? (RangeValues values) {
                                startHeight = values.start.toInt();
                                endHeight = values.end.toInt();
                                setState(() {});
                              }
                            : null,
                      ),
                    )
                  ],
                ).marginOnly(top: 20.w),
                Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("体重",
                            style: kTextStyle(COLOR.white, fontsize: 12.w)),
                        Text(
                            startWeight == 0 && endWeight == 220
                                ? "不限"
                                : "$startWeight-${endWeight}kg",
                            style: kTextStyle(
                                enableQuery
                                    ? COLOR.hexColor("#B93FFF")
                                    : COLOR.white,
                                fontsize: 12.w)),
                      ],
                    ).marginBottom(12.w),
                    SizedBox(
                      width: 400.w,
                      child: RangeSlider(
                        values: RangeValues(
                            startWeight.toDouble(), endWeight.toDouble()),
                        min: 0,
                        max: 220,
                        onChanged: enableQuery
                            ? (RangeValues values) {
                                startWeight = values.start.toInt();
                                endWeight = values.end.toInt();
                                setState(() {});
                              }
                            : null,
                      ),
                    )
                  ],
                ).marginOnly(top: 20.w, bottom: 20.w),
                Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("年龄",
                            style: kTextStyle(COLOR.white, fontsize: 12.w)),
                        Text(
                            startAge == 0 && endAge == 70
                                ? "不限"
                                : "$startAge-$endAge 岁",
                            style: kTextStyle(
                                enableQuery
                                    ? COLOR.hexColor("#B93FFF")
                                    : COLOR.white,
                                fontsize: 12.w)),
                      ],
                    ).marginBottom(12.w),
                    SizedBox(
                      width: 400.w,
                      child: RangeSlider(
                        values:
                            RangeValues(startAge.toDouble(), endAge.toDouble()),
                        min: 0,
                        max: 70,
                        onChanged: enableQuery
                            ? (RangeValues values) {
                                startAge = values.start.toInt();
                                endAge = values.end.toInt();
                                setState(() {});
                              }
                            : null,
                      ),
                    )
                  ],
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "他是",
                      style: kTextStyle(COLOR.white, fontsize: 12.w),
                    ).marginBottom(12.w),
                    Wrap(
                      spacing: 20.w,
                      runSpacing: 10.w,
                      children:
                          List.generate(controller.preferItems.length, (index) {
                        String item = controller.preferItems[index];
                        return Container(
                          width: 75.w,
                          height: 28.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: prefer == item
                                  ? COLOR.hexColor("#423765")
                                  : COLOR.color_1D1D1D,
                              borderRadius: BorderRadius.circular(4.w)),
                          child: Text(item,
                              style: kTextStyle(
                                  prefer == item
                                      ? COLOR.playerThemColor
                                      : Colors.white,
                                  fontsize: 12.w)),
                        ).onTap(() {
                          if (enableQuery) {
                            prefer = item;
                            setState(() {});
                          }
                        });
                      }).toList(),
                    )
                  ],
                ).marginTop(20.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "体型",
                      style: kTextStyle(COLOR.white, fontsize: 12.w),
                    ).marginBottom(12.w),
                    Wrap(
                      spacing: 20.w,
                      runSpacing: 10.w,
                      children: List.generate(controller.bodyShapeItems.length,
                          (index) {
                        String item = controller.bodyShapeItems[index];
                        return Container(
                          width: 75.w,
                          height: 28.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: bodyShape == item
                                  ? COLOR.hexColor("#423765")
                                  : COLOR.color_1D1D1D,
                              borderRadius: BorderRadius.circular(4.w)),
                          child: Text(item,
                              style: kTextStyle(
                                  bodyShape == item
                                      ? COLOR.playerThemColor
                                      : Colors.white,
                                  fontsize: 12.w)),
                        ).onTap(() {
                          if (enableQuery) {
                            bodyShape = item;
                            setState(() {});
                          }
                        });
                      }).toList(),
                    )
                  ],
                ).marginTop(20.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "感情状况",
                      style: kTextStyle(COLOR.white, fontsize: 12.w),
                    ).marginBottom(12.w),
                    Wrap(
                      spacing: 20.w,
                      runSpacing: 10.w,
                      children: List.generate(controller.emotionItems.length,
                          (index) {
                        String item = controller.emotionItems[index];
                        return Container(
                          width: 75.w,
                          height: 28.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: emotion == item
                                  ? COLOR.hexColor("#423765")
                                  : COLOR.color_1D1D1D,
                              borderRadius: BorderRadius.circular(4.w)),
                          child: Text(item,
                              style: kTextStyle(
                                  emotion == item
                                      ? COLOR.playerThemColor
                                      : Colors.white,
                                  fontsize: 12.w)),
                        ).onTap(() {
                          if (enableQuery) {
                            emotion = item;
                            setState(() {});
                          }
                        });
                      }).toList(),
                    )
                  ],
                ).marginTop(20.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "交友目的",
                      style: kTextStyle(COLOR.white, fontsize: 12.w),
                    ).marginBottom(12.w),
                    Wrap(
                      spacing: 20.w,
                      runSpacing: 10.w,
                      children: List.generate(controller.intentionItems.length,
                          (index) {
                        String item = controller.intentionItems[index];
                        return Container(
                          width: 75.w,
                          height: 28.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: intention == item
                                  ? COLOR.hexColor("#423765")
                                  : COLOR.color_1D1D1D,
                              borderRadius: BorderRadius.circular(4.w)),
                          child: Text(item,
                              style: kTextStyle(
                                  intention == item
                                      ? COLOR.playerThemColor
                                      : Colors.white,
                                  fontsize: 12.w)),
                        ).onTap(() {
                          if (enableQuery) {
                            intention = item;
                            setState(() {});
                          }
                        });
                      }).toList(),
                    )
                  ],
                ).marginTop(20.w)
              ],
            )),
            Container(
              width: 360.w,
              height: 42.w,
              margin: EdgeInsets.only(bottom: 16.w),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(41.w),
                  gradient: LinearGradient(colors: [
                    COLOR.hexColor("#A62DE4"),
                    COLOR.hexColor("#D47FFF")
                  ])),
              child: Text(
                "确认",
                style: kTextStyle(Colors.white,
                    fontsize: 18.w, weight: FontWeight.w500),
              ),
            ).onOpaqueTap(() {
              Get.back(
                  result: QueryModel(
                enableQuery: enableQuery,
                loadType: controller.currentIndex.value + 1,
                bodyShape: bodyShape,
                emotion: emotion,
                endAge: endAge,
                endHeight: endHeight,
                endWeight: endWeight,
                intention: intention,
                prefer: prefer,
                startAge: startAge,
                startHeight: startHeight,
                startWeight: startWeight,
              ));
            })
          ],
        ),
      );
    }), isDismissible: false, isScrollControlled: true);
  }

  @override
  void dispose() {
    streamSubscription?.cancel();
    clearLocationEvent?.cancel();
    super.dispose();
  }
}
